<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>测试到达时间显示</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 20px;
      max-width: 800px;
      margin: 0 auto;
      background-color: #f5f5f5;
    }

    .container {
      background: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      margin-bottom: 20px;
    }

    h1,
    h2 {
      color: #333;
      border-bottom: 2px solid #409EFF;
      padding-bottom: 10px;
    }

    .form-group {
      margin-bottom: 15px;
    }

    label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
      color: #555;
    }

    input {
      width: 100%;
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
    }

    button {
      background: #409EFF;
      color: white;
      padding: 10px 20px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      margin-right: 10px;
    }

    button:hover {
      background: #337ecc;
    }

    .result {
      margin-top: 20px;
      padding: 15px;
      border: 1px solid #e6e6e6;
      border-radius: 4px;
      background: #fafafa;
      white-space: pre-wrap;
      font-family: monospace;
      max-height: 400px;
      overflow-y: auto;
    }

    .error {
      color: #F56C6C;
      background: #FEF0F0;
      padding: 10px;
      border-radius: 4px;
      margin: 10px 0;
    }

    .success {
      color: #67C23A;
      background: #F0F9FF;
      padding: 10px;
      border-radius: 4px;
      margin: 10px 0;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 15px;
    }

    th,
    td {
      padding: 8px 12px;
      text-align: left;
      border-bottom: 1px solid #eee;
    }

    th {
      background: #f8f9fa;
      font-weight: bold;
    }

    .time-info {
      background: #e8f4fd;
      padding: 10px;
      border-radius: 4px;
      margin: 10px 0;
    }
  </style>
</head>

<body>
  <div class="container">
    <h1>🕐 测试到达时间显示</h1>

    <div class="form-group">
      <label for="billNo">运单编号:</label>
      <input type="text" id="billNo" placeholder="例如: YD202412250001" value="YD202412250001">
    </div>

    <button onclick="testArrivalTime()">测试到达时间</button>
    <button onclick="updateArrivalTime()">更新到达时间</button>
    <button onclick="clearResult()">清空结果</button>
  </div>

  <div class="container">
    <h2>📋 测试结果</h2>
    <div id="result"></div>
  </div>

  <script>
    const baseURL = 'http://localhost:8080';

    function showResult (title, data) {
      const resultDiv = document.getElementById('result');
      resultDiv.innerHTML = `
                <h3>${title}</h3>
                <div class="result">${JSON.stringify(data, null, 2)}</div>
            `;
    }

    function showError (message) {
      document.getElementById('result').innerHTML = `<div class="error">❌ 错误: ${message}</div>`;
    }

    function showSuccess (message) {
      document.getElementById('result').innerHTML = `<div class="success">✅ ${message}</div>`;
    }

    function clearResult () {
      document.getElementById('result').innerHTML = '';
    }

    // 测试到达时间显示
    async function testArrivalTime () {
      const billNo = document.getElementById('billNo').value;
      if (!billNo) {
        showError('请输入运单编号');
        return;
      }

      try {
        console.log('测试到达时间显示，运单编号:', billNo);

        // 查询运输计划
        const response = await fetch(`${baseURL}/system/plan/list?billNo=${encodeURIComponent(billNo)}`);
        const data = await response.json();

        console.log('查询结果:', data);

        let resultHtml = `
                    <h3>🕐 到达时间显示测试结果</h3>
                    <div class="time-info">
                        <strong>说明：</strong>
                        <ul>
                            <li>如果到达时间只显示日期（如：08-17），说明数据库字段类型是date</li>
                            <li>如果到达时间显示日期和时分（如：08-17 14:30），说明数据库字段类型是datetime</li>
                            <li>如果显示"-"，说明该记录的到达时间为空</li>
                        </ul>
                    </div>
                    <div class="result">API响应: ${JSON.stringify(data, null, 2)}</div>
                `;

        if (data.code === 200) {
          if (data.rows && data.rows.length > 0) {
            resultHtml += `
                            <div class="success">✅ 找到 ${data.rows.length} 条运输计划记录</div>
                        `;

            // 显示到达时间表格
            resultHtml += `
                            <h4>到达时间详情:</h4>
                            <table>
                                <thead>
                                    <tr>
                                        <th>序号</th>
                                        <th>城市</th>
                                        <th>节点类型</th>
                                        <th>原始到达时间</th>
                                        <th>格式化后时间</th>
                                        <th>数据类型</th>
                                    </tr>
                                </thead>
                                <tbody>
                        `;

            data.rows.forEach((plan, index) => {
              const originalTime = plan.arrivalTime;
              const formattedTime = formatTime(originalTime);
              const dataType = getDataType(originalTime);

              resultHtml += `
                                <tr>
                                    <td>${index + 1}</td>
                                    <td>${plan.city || '-'}</td>
                                    <td>${plan.nodeType || '-'}</td>
                                    <td>${originalTime || 'null'}</td>
                                    <td>${formattedTime}</td>
                                    <td>${dataType}</td>
                                </tr>
                            `;
            });

            resultHtml += `
                                </tbody>
                            </table>
                        `;
          } else {
            resultHtml += `
                            <div class="error">❌ 未找到运输计划记录</div>
                        `;
          }
        } else {
          resultHtml += `
                        <div class="error">❌ 查询失败: ${data.msg || '未知错误'}</div>
                    `;
        }

        document.getElementById('result').innerHTML = resultHtml;

      } catch (error) {
        console.error('测试异常:', error);
        showError('测试异常: ' + error.message);
      }
    }

    // 格式化时间
    function formatTime (timeStr) {
      if (!timeStr) return '-';

      try {
        const date = new Date(timeStr);
        if (isNaN(date.getTime())) return '无效时间';

        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');

        return `${month}-${day} ${hours}:${minutes}`;
      } catch (error) {
        return '格式化失败';
      }
    }

    // 判断数据类型
    function getDataType (timeStr) {
      if (!timeStr) return 'null';

      if (timeStr.includes('T') || timeStr.includes(' ')) {
        return 'datetime';
      } else if (timeStr.match(/^\d{4}-\d{2}-\d{2}$/)) {
        return 'date';
      } else {
        return 'unknown';
      }
    }

    // 更新到达时间（添加时分）
    async function updateArrivalTime () {
      const billNo = document.getElementById('billNo').value;
      if (!billNo) {
        showError('请输入运单编号');
        return;
      }

      try {
        showResult('更新到达时间', '开始更新...');

        // 1. 先查询现有数据
        const response = await fetch(`${baseURL}/system/plan/list?billNo=${encodeURIComponent(billNo)}`);
        const data = await response.json();

        if (data.code !== 200 || !data.rows || data.rows.length === 0) {
          showError('未找到运输计划数据');
          return;
        }

        // 2. 更新每条记录的到达时间
        const updateResults = [];

        for (let i = 0; i < data.rows.length; i++) {
          const plan = data.rows[i];

          // 为每条记录设置不同的到达时间（模拟实际到达时间）
          const baseDate = new Date();
          baseDate.setDate(baseDate.getDate() + i + 1); // 每天递增
          baseDate.setHours(8 + i * 2, 30 + i * 15, 0, 0); // 设置时分

          const updateData = {
            id: plan.id,
            arrivalTime: baseDate.toISOString().slice(0, 19).replace('T', ' ')
          };

          console.log(`更新第${i + 1}条记录:`, updateData);

          const updateResponse = await fetch(`${baseURL}/system/plan`, {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(updateData)
          });
          const updateResult = await updateResponse.json();

          updateResults.push({
            index: i,
            planId: plan.id,
            city: plan.city,
            originalTime: plan.arrivalTime,
            newTime: updateData.arrivalTime,
            result: updateResult
          });
        }

        showResult('到达时间更新结果', updateResults);

        // 3. 重新测试显示
        setTimeout(() => {
          testArrivalTime();
        }, 1000);

      } catch (error) {
        console.error('更新异常:', error);
        showError('更新异常: ' + error.message);
      }
    }

    // 页面加载完成后的初始化
    document.addEventListener('DOMContentLoaded', function () {
      console.log('到达时间测试页面已加载');
    });
  </script>
</body>

</html>